const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            ID_Card: [],
            dataForm: {
                Party_Member_SerialNumber: '',
                Personal_Resource: '1',
                Political_Affiliation: '中共党员'
            },
            dataForm1: {
                RR_County_Nubmer: '232723',
                Personal_Resource: '1',
                Political_Affiliation: '中共党员'
            },
            showDialog: false,
            fileUrl: '',
            childDataForm: [{
                Type: 0,
                fileList: [],
                Children: {
                    party_member_event_attachment: [],
                }
            }, {
                Type: 1,
                fileList: [],
                Children: {
                    party_member_event_attachment: [],
                }
            }],
            childDataForm1: [],
            rules: {
                // 身份证编号验证（空值+格式）
                ID_Card_Number: [
                    {
                        required: true,
                        message: "身份证编号不能为空",
                        trigger: "blur",
                    },
                    {
                        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                        message: "身份证格式不正确",
                        trigger: "blur",
                    },
                ],
                Position: [        // 党内职务（空值校验）
                    {
                        required: true,
                        message: "请选择党内职务",
                        trigger: "change",
                    },
                ],
                // 入党日期（空值+日期格式）
                Joining_Date: [
                    {
                        required: true,
                        message: "请选择入党日期",
                        trigger: "change",
                    },
                    {
                        type: "date",
                        message: "日期格式不正确",
                        trigger: "change",
                    },
                ],
                // 转正日期（空值+日期格式）
                Conformation_Date: [
                    {
                        required: true,
                        message: "请选择转正日期",
                        trigger: "change",
                    },
                    {
                        type: "date",
                        message: "日期格式不正确",
                        trigger: "change",
                    },
                ],
                Party_Organization_SerialNumber: [
                    {
                        required: true,
                        message: "党组织不能为空",
                        trigger: "blur",
                    },
                ],
            },
            Affiliation: [
                {
                    value: "部长",
                    label: "部长",
                },
                {
                    value: "副部长",
                    label: "副部长",
                },
                {
                    value: "科长",
                    label: "科长",
                },
                {
                    value: "科员",
                    label: "科员",
                },
            ],
            Manager: [],
            Nation: [],
            fileList: [],
            Ducation: ducation(),
            city: [],
            city1: [],
            cityValue: [],
            Category: [],
            Position: [],
            is: false,
            childDataForm2: [],
        };
    },
    mounted() {
        this.getCategory();
        this.changeCity(this.dataForm1.RR_County_Nubmer)
    },
    watch: {
        'dataForm.ID_Card_Number'(val) {
            this.dataForm1.ID_Card_Number = val;
        },
        'dataForm.Party_Member_SerialNumber'() {
            if (this.action == 'Modify') {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: "personal_information", //表名
                        Condition: "ID_Card_Number='" + this.dataForm.ID_Card_Number + "'",
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            this.dataForm1 = res[0];
                            this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer, this.dataForm1.RR_Town_Number];
                            this.is = false;
                        } else {
                            this.is = true;
                        }
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                });
            }
        },
        childDataForm(val) {
            console.log(val);
        }
    },
    methods: {
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.location.href = photo + row.Attachment_URL;
            // }
            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        shibie(val) {
            if (this.action == 'Add') {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableName`,
                    method: "post",
                    data: {
                        Data: "personal_information", //表名
                        Condition: "ID_Card_Number='" + val + "'",
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            this.dataForm1 = res[0];
                            this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer, this.dataForm1.RR_Town_Number];
                            this.is = false;
                        } else {
                            if (ID_Validity(val)) {
                                this.dataForm1.Gender = Return_SexByID(val)
                                this.dataForm1.Birthday = Return_BirthdayByID(val)
                            }
                            this.is = true;
                        }
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                });
            }
        },
        getData(nodeKey) {//查询
            const { primary_key } = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'party_member_information',
                    Condition: `${primary_key}='${nodeKey}'`,
                },
                success: (res) => {
                    console.log(res);
                    this.dataForm = res[0];
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'party_member_event',
                    Condition: `${primary_key}='${nodeKey}'`,
                },
                success: (res) => {
                    let str = res.map(i => "'" + i.Event_SerialNumber + "'").join(',')
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        method: "post",
                        data: {
                            Data: 'party_member_event_attachment',
                            Condition: `Event_SerialNumber IN (${str})`,
                        },
                        success: (data) => {
                            res.forEach(item => {
                                let party_member_event_attachment = data.filter(i => i.Event_SerialNumber == item.Event_SerialNumber);
                                let arr = [];
                                party_member_event_attachment.forEach(item => {
                                    item.name = item.Attachment_Name + "（磁盘文件名:" + item.Attachment_URL + "）"
                                    arr.push(item)
                                })
                                item.fileList = arr;
                                item.Children = {
                                    party_member_event_attachment,
                                }
                            })
                            this.childDataForm = res;
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest)
                        },
                    });
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'party_member_information_attachment',
                    Condition: `${primary_key}='${nodeKey}'`,
                },
                success: (res) => {
                    let arr = [];
                    res.forEach(item => {
                        item.name = item.Attachment_Name + "（磁盘文件名:" + item.Attachment_URL + "）"
                        arr.push(item)
                    })
                    this.fileList = arr;
                    this.childDataForm1 = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                type: "POST",
                url: mh + "/generalBusiness/generalQueryByTableName",
                data: {
                    Data: "party_member_position", //指定要查询的数据库表名
                    Condition: "", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
                },
                success: (Result) => {
                    this.Position = Result;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        changeCity(val) {
            if (val) {
                this.dataForm1.RR_Province_Number = val.substring(0, 2) + '0000';
                this.dataForm1.RR_City_Number = val.substring(0, 4) + '00';
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/clientOperation/getDistrictTree`,
                    type: "GET",
                    data: {
                        DistrictCode: val,
                    },
                    success: (data) => {
                        this.city1 = data[0].children;
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            } else {
                this.dataForm1.Registered_Residence = '';
                this.dataForm1.RR_Province_Number = '';
                this.dataForm1.RR_City_Number = '';
                this.dataForm1.RR_County_Nubmer = '';
                this.dataForm1.RR_Town_Number = '';
                this.dataForm1.RR_Village_Number = '';
            }
        },
        changeCity1(val) {
            let Province = this.city.filter(i => i.value == (val.substring(0, 2) + '0000'))[0];
            let City = Province.children.filter(i => i.value == (val.substring(0, 4) + '00'))[0];
            let County = City.children.filter(i => i.value == (val.substring(0, 6)))[0];
            let Town = this.city1.filter(i => i.ProvinceNumber == (val.substring(0, 9)))[0];
            let Village = Town.children.filter(i => i.ProvinceNumber == val)[0];
            this.dataForm1.Registered_Residence = Province.label + City.label + County.label + Town.Province + Village.Province;
            this.dataForm1.RR_Town_Number = val.substring(0, 9);
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        if (this[ls_DataForm][ls_primary_key]) {
                            this[ls_ChildDataForm].forEach(item => {
                                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                            })
                        }
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONObject_Table = new Object();
                    if (this.is) {
                        this['dataForm1']['Children'] = {
                            party_member_information: [deepClone(this[ls_DataForm])]
                        }
                        let lJSONArray_Record = new Array();
                        lJSONArray_Record.push(this['dataForm1']);
                        lJSONObject_Table['personal_information'] = lJSONArray_Record;
                    } else {
                        let lJSONArray_Record = new Array();
                        lJSONArray_Record.push(this[ls_DataForm]);
                        lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    }
                    lJSONObject_Table['party_member_category_log'] = [{
                        Party_Member_Category_SerialNumber: this.dataForm.Party_Member_Category_SerialNumber,
                    }]
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_Table['personal_information'] = [this.dataForm1];

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                    lJSONObject_DataSet['Add'] = {
                        party_member_event_attachment: this.childDataForm2
                    }
                    if (this[ls_DataForm].Party_Member_Category_SerialNumber != this[ls_DataForm].Party_Member_Category_SerialNumber_Original) {
                        let party_member_category_log = [{
                            Party_Member_Category_SerialNumber: this.dataForm.Party_Member_Category_SerialNumber,
                            Party_Member_SerialNumber: this.dataForm.Party_Member_SerialNumber,
                        }]
                        lJSONObject_DataSet['Add'] = {
                            party_member_category_log,
                        }
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSave",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                    }
                    this.loading = false;
                })
            }
        },
        getCategory() {
            $.ajax({
                url: absolutepath() + "api/Nation.json",
                type: "GET",
                success: (data) => {
                    this.Nation = data;
                },
                dataType: "json",
            });
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach((item) => {
                        item.children.forEach((ite) => {
                            ite.children.forEach((it) => {
                                it.children = undefined;
                            });
                        });
                    });
                    this.city = data;
                }
            });
            const { primary_key } = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'party_member_attachment',
                    Condition: `${primary_key}='${this.nodeKey}' AND Row_Status='0' AND File_Type='3'`,
                },
                success: (res) => {
                    this.childDataForm1 = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                type: "POST",
                url: mh + "/generalBusiness/generalQueryByTableName",
                data: {
                    Data: "party_member_position", //指定要查询的数据库表名
                    Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
                },
                success: (Result) => {
                    this.Position = Result;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                type: "POST",
                url: mh + "/generalBusiness/generalQueryByTableName",
                data: {
                    Data: "party_member_category", //指定要查询的数据库表名
                    Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
                },
                success: (Result) => {
                    this.Category = Result;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                type: "POST",
                url: mh + "/generalBusiness/generalQueryByTableNameWithOriginal",
                data: {
                    Data: "personal_information", //指定要查询的数据库表名
                    Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
                },
                success: (Result) => {
                    this.ID_Card = Result;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'party_organization',
                    NodeCode: '',
                },
                success: (data) => {
                    this.Manager = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        handleAdd(Type) {
            this.childDataForm.push({
                Type,
                fileList: [],
                Children: {
                    party_member_event_attachment: [],
                }
            })
        },
        handleRemove(Type) {
            if (this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type).length > 1) {
                let i = this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type).length - 1
                let obj = this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type)[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this.childDataForm = this.childDataForm.filter((x, id) => x.Type == Type && id != i);
                } else {
                    this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.childDataForm.filter(item => item.Row_Status != '1' && item.Type == Type)[i].Row_Status = '1'
                    }).catch(() => {
                        this.$message({
                            type: 'warning',
                            message: '已取消删除'
                        });
                    });
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        success(row, res, arr, id, value) {
            //添加正常主子表提交
            if (!value) {
                let obj = {
                    uid: row.uid,
                    Attachment_URL: res.fileName,
                    Attachment_Name: row.name,
                    Temp_Path: res.tempPath,
                }
                obj[id] = value;
                arr.push(obj)
            } else {//添加直接上传新表，因为有主键
                let obj = {
                    uid: row.uid,
                    Attachment_URL: res.fileName,
                    Attachment_Name: row.name,
                    Temp_Path: res.tempPath,
                }
                obj[id] = value;
                if (id == 'Party_Member_SerialNumber') {
                    arr.push(obj);
                } else {
                    this.childDataForm2.push(obj);
                }
            }
        },
        remove(row, res, arr, id, value) {
            if (this.action == 'Add') {
                arr = arr.filter(i => i.uid != row.uid);
            } else {
                if (!Object.keys(row).some(item => item.includes('_Original'))) {
                    if (id == 'Party_Member_SerialNumber') {
                        arr = arr.filter(i => i.uid != row.uid);
                    } else {
                        this.childDataForm2 = this.childDataForm2.filter(i => i.uid != row.uid);
                    }
                } else {
                    let obj = arr.filter(i => i[id] == row[id])[0];
                    obj.Row_Status = '1'
                }
            }
        }
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader);
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
